#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/4 11:51
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : interfaceRequest.py
import requests
import json
from common.logger import Log
import requests
from testcase.asserts.responseCodeCheck import ResponseCodeCheck

logger = Log()
# session = requests.session()
class CheckResult:

    def checkResult(self,session,headers_token,url,datatype,method,code_suc,param):
        global info
        try:
            logger.info(f'请求方法：{method}')
            logger.info(f'请求路径：{url}')
            logger.info(f'请求参数：{param}')

            if method == "POST":
                info = self.__post(session,url,param,headers_token,datatype)
            if method == "GET":
                info = self.__get(session,url, param, headers_token)
            if method == "PUT":
                pass
            if method == "DELETE":
                pass

            respTime = info.elapsed.total_seconds()
            logger.info(f"响应时间：{respTime}")
            respStatus = info.status_code
            logger.info(f"响应状态：{respStatus,type(respStatus)}")
            respText = info.text
            logger.info(f"响应结果：{respText}")
            # 断言
            ResponseCodeCheck().code_all(respStatus,respText,code_suc)
            return info
        except Exception as e:
            logger.info(f"请求异常：{e}")

    def __get(self,session,url,param,headers_token):
        params = json.loads(param)
        return session.get(url=url, params=params, headers=headers_token)

    def __post(self,session,url,param,headers_token,datatype):
        if param:
            if datatype == 'JSON':
                try:
                    headers_token['Content-Type'] = 'application/json' #post请求参数为json格式
                    print(headers_token)
                    return self.__post_json(session, url, param, headers_token)
                except Exception as e:
                    logger.info(f"请求异常：{e}")

            elif datatype == 'FORM':
                try:
                    return self.__post_form(session, url, param, headers_token)
                except Exception as e:
                    logger.info(f"请求异常：{e}")
            else:
                try:
                    return self.__post_else(session, url, param, headers_token)
                except Exception as e:
                    logger.info(f"请求异常：{e}")
        else:
            return session.post(url=url, headers=headers_token)

    def __post_json(self,session,url,param,headers_token):
        '''
        常见的form表单可以直接使用data参数进行报文提交，而data的对象则是python中的字典类型；
        而在最新爬虫的过程中遇到了一种payload报文，是一种json格式的报文，因此传入的报文对象也应该是格式的；这里有两种方法进行报文提交：
        例子
        data = {
            'a': 1,
            'b': 2,
            }
        1 - data参数需要使用json.dumps将字典类型的对象转换成json格式的字符串对象
        r1 = requests.post(url, data=json.dumps(data))
        2 - json参数会自动将字典类型的对象转换为json格式
        r2 = requests.post(url, json=data)
        :param url:
        :param param:
        :param headers_token:
        :return:
        '''
        return session.post(url=url,data=json.dumps(eval(param)),headers=headers_token)

    def __post_form(self,session,url,param,headers_token):
        return session.post(url=url, data=json.loads(param), headers=headers_token)

    def __post_else(self,session,url,param,headers_token):
        return session.post(url=url, data=param, headers=headers_token)


if __name__ == '__main__':
    # dic = '{"key":"value","key1":"value1"}'
    # print(type(json.dumps(dic)))
    from common.headers import GetToken
    s = requests.session()
    session,headers_token = GetToken().login_token(s)
    param = '{"robotId":"4d472b34ab084aa4a6fb3e954bf33420","execStatus":2}'

    result = CheckResult().checkResult(session,headers_token,"https://chenguang.cloud:8080/api/robotTask","JSON","GET","11",param)
    print(result.text)